package com.lajiaomian.springbootruijiwaimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lajiaomian.springbootruijiwaimai.common.BaseContext;
import com.lajiaomian.springbootruijiwaimai.common.R;
import com.lajiaomian.springbootruijiwaimai.pojo.Category;
import com.lajiaomian.springbootruijiwaimai.service.impl.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author lajiaomian
 * @create 2022-08-12-22:39
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 保存菜品类别
     * @param category
     * @param session
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category,HttpSession session){
        BaseContext.setCurrId((Long) session.getAttribute("employee"));
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 分页展示菜品信息
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize){
        Page categoryPage = categoryService.getCategoryPage(page, pageSize);
        return R.success(categoryPage);
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String > delete( Long ids){
        //完善：需要判断是否有关联的菜品，有则无法删除
        if(ids!=null){
            categoryService.remove(ids);
            return R.success("删除成功");
        }
        return R.error("id不存在");
    }

    /**
     * 修改菜品
     * @param category
     * @param session
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category,HttpSession session){
        Long empId = (Long) session.getAttribute("employee");
        BaseContext.setCurrId(empId);
        categoryService.updateById(category);
        return R.success("更新成功");
    }

    /**
     * 用户页展示菜品分类
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //获取type类型
        Integer type = category.getType();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(type != null,"type",type);
        wrapper.orderByAsc("sort");
        wrapper.orderByDesc("update_time");
        List list = categoryService.list(wrapper);
        return R.success(list);
    }

}
